package file

import (
	"io"
	"os"
	"path/filepath"
	"time"
)

type LocalConfig struct {
	StorageDir string `yaml:"storage_dir"`
	BrowseDir string `yaml:"browse_dir"`
}

type LocalStorage struct {
	LocalConfig
}

func (s *LocalStorage) Path(name string) (storage, browse string) {
	date := time.Now().Format("20060102")
	name = date+"/"+name
	return s.StorageDir+name, s.BrowseDir+name
}

func (s *LocalStorage) Save(path string, reader io.Reader) (err error) {
	if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
		return err
	}
	dest, err := os.Create(path)
	if err != nil {
		return err
	}
	defer dest.Close()
	_, err = io.Copy(dest, reader)
	return err
}

func NewLocalStorage(c LocalConfig) *LocalStorage {
	return &LocalStorage{LocalConfig:c}
}